package com.atguigu.jdbc3;

import com.atguigu.jdbc.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchDemo {
/*
未批处理
 */
    @Test
    public void insert() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql="insert into demo1(id,username) values(?,?)";
        PreparedStatement ps =null;
            ps = connection.prepareStatement(sql);
        for (int i = 1; i <= 100000; i++) {

            ps.setInt(1,i);
            ps.setString(2,"wzx"+i);
            ps.executeUpdate();
        }
        JDBCUtils.close(ps,connection);
    }
    @Test
    public void insert1() throws SQLException {
        Connection connection = JDBCUtils.getConnection();

        String sql="insert into demo1 values(?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        for (int i = 0; i < 100000; i++) {
            ps.setInt(1,i);
            ps.setString(2,"wzx"+i);
            //将需要执行的sql操作放批处理中
            ps.addBatch();
            if(i%10000==0){
                //执行批处理
                ps.executeBatch();
                //清空批处理
                ps.clearBatch();
            }
        }
        JDBCUtils.close(ps,connection);
    }
}
